<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
            <!-- 步骤条区域 -->
            <el-steps :space="200" :active="activeindex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- 把tabs标签页区域用form表单包裹 -->
            <el-form :model="AddForm" :rules="AddRules" ref="AddFormRef" label-width="100px" label-position="top">
                <!-- tabs标签页区域 -->
                <el-tabs v-model="activeindex" :tab-position="'left'" :before-leave="stopTabs" @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="AddForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="AddForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="AddForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="AddForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <!-- 级联选择器 -->
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader expand-trigger="hover" v-model="AddForm.goods_cat" :options="CatesList"
                                :props="catesProps" @change="cateshandleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="(item,i) in manyTableData" :key="item.attr_id">
                            <!-- 多选框 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- Upload图片上传 -->
                        <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload"
                            :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture"
                            :headers="headersobj" :on-success="uploadSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器 -->
                        <quill-editor v-model="AddForm.goods_introduce"></quill-editor>
                        <!-- button按钮 -->
                        <el-button class="btn" type="primary" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

        </el-card>
        <!-- 图片预览的对话框 -->
        <el-dialog title="图片预览" :visible.sync="ImagedialogVisible" width="50%">
            <img :src="ImagePath" alt="" class="ImageStyle">
        </el-dialog>
    </div>
</template>
<script>
//导入lodash深拷贝
import _ from 'lodash'
    export default {
        data() {
            return {
                activeindex: "0",
                //添加商品的表单数据对象
                AddForm: {
                    goods_name: '',
                    goods_price: 0,
                    goods_weight: 0,
                    goods_number: 0,
                    //商品所属的分类数组
                    goods_cat: [],
                    //存放图片的数组
                    pics: [],
                    goods_introduce:'',
                    //存放动态参数以及静态属性的数组
                    attrs:[],



                },
                //添加商品的表单验证规则对象
                AddRules: {
                    goods_name: [{
                        required: true,
                        message: '请输入商品名称',
                        trigger: 'blur'
                    }, ],
                    goods_price: [{
                        required: true,
                        message: '请输入商品价格',
                        trigger: 'blur'
                    }, ],
                    goods_weight: [{
                        required: true,
                        message: '请输入商品重量',
                        trigger: 'blur'
                    }, ],
                    goods_number: [{
                        required: true,
                        message: '请输入商品数量',
                        trigger: 'blur'
                    }, ],
                    goods_cat: [{
                        required: true,
                        message: '请选择商品分类',
                        trigger: 'blur'
                    }, ]

                },
                //存放商品列表数据的数组
                CatesList: [],
                //级联选择器的配置对象
                catesProps: {
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children'
                },
                //参数面板数据数组
                manyTableData: [],
                //静态属性列表数据
                onlyTableData: [],
                //因为Upload上传组件没有调用axios,所以应该为图片上传手动设置请求头
                headersobj: {
                    Authorization: window.sessionStorage.getItem('token')
                },
                //控制图片预览对话框的显示与隐藏
                ImagedialogVisible:false,
                //预览图片的路径
                ImagePath:'',
            }
        },
        created() {
            this.getCateList();

        },
        methods: {
            //获取商品分类列表数据
            async getCateList() {
                //发起请求
                const {
                    data: res
                } = await this.$http.get('categories');
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取商品列表数据失败');
                }
                this.CatesList = res.data;
            },
            //级联选择器选中项发生变化触发的函数
            cateshandleChange() {
                console.log(this.AddForm.goods_cat);
                //控制级联选择器的选中范围，只允许选中三级分类
                if (this.AddForm.goods_cat.length !== 3) {
                    this.AddForm.goods_cat = [];
                }
            },
            //当oldActiveName即将离开的标签的索引是第一个标签页的索引时，同时级联选择器没有选中三级商品分类时，阻止标签页切换
            stopTabs(activeName, oldActiveName) {
                if (oldActiveName === '0' && this.AddForm.goods_cat.length !== 3) {
                    this.$message.error('请先选择商品分类')
                    return false;
                }
            },
            //tabs面板切换触发的事件
            async tabClicked() {
                if (this.activeindex === '1') {
                    //发起请求，请求商品参数面板数据
                    const {
                        data: res
                    } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: {
                            sel: 'many'
                        }
                    });
                    console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('获取动态参数列表数据失败')
                    }
                    console.log(res.data);
                    //将res.data中的attr_vals字符串转化为数组
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
                    })
                    this.manyTableData = res.data;
                } else if (this.activeindex === '2') {
                    //发起请求，获取静态属性列表数据
                    const {
                        data: res
                    } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: {
                            sel: 'only'
                        }
                    })
                    console.log(res, "111");
                    if (res.meta.status !== 200) {
                        return this.$message.error('获取静态属性列表数据失败')
                    }
                    this.onlyTableData = res.data;
                }
            },
            //图片预览时触发的事件
            handlePreview(file) {
                this.ImagedialogVisible=true;
                console.log(file);
                this.ImagePath=file.response.data.url;

            },
            //点击删除图片触发的事件
            handleRemove(file) {
                console.log(file);
                //1.获取将要删除的图片的临时路径
                const filePath = file.response.data.tmp_path;
                //2.从pics数组中找到这张图片对应的索引
                const i = this.AddForm.pics.findIndex(x => x.pic === 'filePath');
                //3.调用数组的splice方法根据索引将该图片移出
                this.AddForm.pics.splice(i, 1);
                console.log(this.AddForm, "222");

            },
            //图片上传成功之后触发的函数
            uploadSuccess(response) {
                console.log(response);
                //1.拼接得到一个图片信息对象
                const picInfo = {
                    pic: response.data.tmp_path
                }
                //2.将图片信息对象push到pics数组中
                this.AddForm.pics.push(picInfo);
                console.log(this.AddForm);

            },
            //点击富文本编辑器中的添加商品按钮
            add(){
                //添加商品之前进行表单的预验证
                this.$refs.AddFormRef.validate(async valid=>{
                    if(!valid){
                        return this.$message.error('请填写必要的表单项');
                    }
                    //发起添加商品的请求
                    //请求前对Addform进行一次深拷贝
                    const newform=_.cloneDeep(this.AddForm);
                    newform.goods_cat=newform.goods_cat.join(',');
                    //请求前处理动态参数
                    this.manyTableData.forEach(item=>{
                        const newInfo={attr_id:item.attr_id,attr_vals:item.attr_vals};
                        this.AddForm.attrs.push(newInfo);
                    })
                    //请求前处理静态属性
                    this.onlyTableData.forEach(item=>{
                        const newInfo={
                            attr_id:item.attr_id,
                            attr_vals:item.attr_vals
                        };
                        this.AddForm.attrs.push(newInfo);
                    })

                    newform.attrs=this.AddForm.attrs;

                    console.log(newform,"111");
                    //正式发起添加商品的请求
                    const {data:res}=await this.$http.post('goods',newform);
                    console.log(res,"111");
                    if(res.meta.status!==200){
                        return this.$message.error('添加商品失败')
                    }
                    this.$message.success('添加商品成功');
                    this.$router.push('/goods');

                })
               
            }

        },
        computed: {
            //获取三级商品分类的id
            cateId() {
                if (this.AddForm.goods_cat.length === 3) {
                    return this.AddForm.goods_cat[2]
                } else {
                    return null;
                }
            }
        }
    }
</script>
<style lang="less" scoped>
    .el-checkbox {
        margin: 0 10px 0 0 !important;
    }
    .ImageStyle{
        width: 100%;
    }
    .btn{
        margin-top: 15px;
    }
</style>